package com.xpxrule.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @version 1.0
 * @Author xiangpengxiang
 * @Date 2025/1/21 19:59
 * @注释
 */
public class FileReadUtil {

    public static String getJsonFromPath(String jsonPath) {
        ClassPathResource resource = new ClassPathResource(jsonPath);
        String jsonData;
        try {
            jsonData = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return jsonData;
    }

    public static <T> T parseFromPath(String jsonPath, TypeReference<T> typeReference) {
        ClassPathResource resource = new ClassPathResource(jsonPath);
        ObjectMapper objectMapper = new ObjectMapper();
        T result;
        String jsonData;
        try {
            jsonData = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
            result = objectMapper.readValue(jsonData, typeReference);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}
